<?php

namespace App\Transformers;

use App\Models\Social;
use League\Fractal\TransformerAbstract;
use Cache;
class SocialTransformer extends TransformerAbstract
{
    protected $state = '';
    public function transform(Social $social)
    {
        return [
            'name' => $social->name,
            'redirect_url' => $this->transUrl($social),
            'icon' => $social->icon,
            'color' => $social->color,
            'state' => $this->state
        ];
    }
    protected function state()
    {
      // 生成 state
      $this->state = $key = str_random(40);
      // 加入缓存
      Cache::put($key, $key, 1); // 1分钟有效期缓存
      return $key;
    }
    protected function transUrl($social)
    {
      $this->state();
      $url = str_replace('{appid}', $social->appid, $social->redirect_url);
      $url = str_replace('{state}', $this->state, $url);
      return str_replace('{redirect_url}', urlencode($social->callback_url . '/'. $social->type), $url);
    }
}
